package com.sgb.kjwl.view.ui.activity.manage;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityAgentStaffCheckDepartmentBinding;
import com.sgb.kjwl.databinding.ItemAgentStaffDepartmentBinding;
import com.sgb.kjwl.di.manage.DaggerEnterpriseManageComponent;
import com.sgb.kjwl.di.manage.EnterpriseManageModule;
import com.sgb.kjwl.model.entity.manage.AgentStaffCheckEntity;
import com.sgb.kjwl.model.entity.manage.CompanyAndDeptEntity;
import com.sgb.link.utils.SizeUtils;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.self.AgentApplyEvent;
import com.sgb.kjwl.viewmodel.manage.AgentStaffCheckDepartmentModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.List;

import javax.inject.Inject;

public class AgentStaffCheckDepartmentActivity extends AppActivity {

    private ActivityAgentStaffCheckDepartmentBinding mBinding;
    private static final String KEY_ENTITY = "key_entity";
    public static final String KEY_DATA = "key_data";
    private static final String KEY_DATAS = "key_data";
    private static final String KET_FIRST_TITLE = "key_first_title";
    private AgentStaffCheckEntity mEntity;

    private AgentStaffDepartmentAdapter mAdapter;

    private TextView tvSecondName;

    private String mComNo;

    private String mFirstName;

    private List<CompanyAndDeptEntity> mDatas;;

    @Inject
    AgentStaffCheckDepartmentModel mViewModel;

    private CompanyAndDeptEntity mSecondCompanyEntity;

    public static void launch(Activity context, int requestCode){
        Intent intent = new Intent();
        intent.setClass(context, AgentStaffCheckDepartmentActivity.class);
        context.startActivityForResult(intent, requestCode);
    }

    public static void launch(Activity context, AgentStaffCheckEntity entity, int requestCode){
        Intent intent = new Intent();
        intent.setClass(context, AgentStaffCheckDepartmentActivity.class);
        intent.putExtra(KEY_ENTITY, entity);
        context.startActivity(intent);
    }

    /**
     * 仅供内部调用
     * @param context
     * @param entity
     * @param firstName
     * @param datas
     */
    public static void launch(Activity context, AgentStaffCheckEntity entity, String firstName, List<CompanyAndDeptEntity> datas){
        Intent intent = new Intent();
        intent.setClass(context, AgentStaffCheckDepartmentActivity.class);
        intent.putExtra(KET_FIRST_TITLE, firstName);
        intent.putExtra(KEY_ENTITY, entity);
        intent.putExtra(KEY_DATAS, (Serializable)datas);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerEnterpriseManageComponent.builder().appComponent(appComponent)
                .enterpriseManageModule(new EnterpriseManageModule()).build().inject(this);
    }

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initView() {
        super.initView();
        if (getIntent() != null) {
            mEntity = (AgentStaffCheckEntity) getIntent().getSerializableExtra(KEY_ENTITY);
            mFirstName = getIntent().getStringExtra(KET_FIRST_TITLE);
            mDatas = (List<CompanyAndDeptEntity>) getIntent().getSerializableExtra(KEY_DATAS);
        }
        if (mEntity == null) {
            finish();
            return;
        }
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_agent_staff_check_department);
        //新员工添加这些信息制空
        if (TextUtils.isEmpty(mFirstName)){
            mEntity.setDeptName("");
            mEntity.setDeptNo("");
            mEntity.setSComName("");
            mEntity.setSComNo("");
        }
        if (mDatas != null){
            mViewModel.departList.postValue(mDatas);
        }
        mBinding.include.ivBack.setOnClickListener(v -> {
            finish();
        });
        mBinding.include.titleView.setText("选择部门");
        mAdapter = new AgentStaffDepartmentAdapter(R.layout.item_agent_staff_department);
        mBinding.recycleView.setAdapter(mAdapter);
        mBinding.recycleView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        updateFirstDepartment(TextUtils.isEmpty(mFirstName) ? mEntity.getComName() : mFirstName, !TextUtils.isEmpty(mFirstName));
        mBinding.refreshLayout.setEnableLoadMore(false);
        mBinding.refreshLayout.setEnableRefresh(false);
        mBinding.tvFinish.setOnClickListener(this);
        mBinding.recycleView.addItemDecoration(
                new RecyclerCustomDecoration(
                        0f,
                        0f,
                        0f,
                        getResources().getDimension(R.dimen.dp1), getResources().getColor(R.color.color_main_bg)
                )
        );
        mAdapter.setCallBack(new OnItemClickCallBack() {
            @Override
            public void changeChooseStats(int position) {
                CompanyAndDeptEntity item;
                List<CompanyAndDeptEntity> data = mAdapter.getData();
                if (!data.isEmpty()){
                    for (int i = 0; i < data.size(); i++) {
                        item = data.get(i);
                        if (item == null){
                            return;
                        }
                        if (i == position){
                            if (!item.isChoose()) {
                                item.setChoose(true);
                                if (mAdapter.isShowRight()) {
                                    mEntity.setSComName(item.getName());
                                    mEntity.setSComNo(item.getId());
                                    updateFirstDepartment(item.getName(), true);
                                } else {
                                    updateSecondDepartment(item.getName(), false);
                                    mEntity.setDeptName(item.getName());
                                    mEntity.setDeptNo(item.getId());
                                }
                            }
                        } else {
                            item.setChoose(false);
                        }
                    }
                }
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void itemClick(int position) {
                CompanyAndDeptEntity item = mAdapter.getItem(position);
                if (mAdapter.isShowRight()){
                    if (!TextUtils.isEmpty(item.getId())){
                        mComNo = item.getId();
                        mViewModel.getDepartmentList(AgentStaffCheckDepartmentActivity.this, item.getId());
                    }
                    updateSecondDepartment("", false);
                } else {
                    if ((item.getChildren() != null && !item.getChildren().isEmpty())) {
                        AgentStaffCheckDepartmentActivity.launch(AgentStaffCheckDepartmentActivity.this, mEntity, item.getName(), item.getChildren());
                    }
                }
                changeChooseStats(position);
            }
        });
        mViewModel.companyList.observe(this, new Observer<List<CompanyAndDeptEntity>>() {
            @Override
            public void onChanged(List<CompanyAndDeptEntity> companyAndDeptEntities) {
                mAdapter.setShowRight(true);
                mAdapter.setNewData(companyAndDeptEntities);
            }
        });
        mViewModel.departList.observe(this, new Observer<List<CompanyAndDeptEntity>>() {
            @Override
            public void onChanged(List<CompanyAndDeptEntity> companyAndDeptEntities) {
                if (companyAndDeptEntities.isEmpty()){
                    MToast.showToast(AgentStaffCheckDepartmentActivity.this, "暂无部门");
                    return;
                }
                mAdapter.setShowRight(false);
                mAdapter.getData().clear();
                mAdapter.getData().addAll(companyAndDeptEntities);
                mBinding.tvFinish.setVisibility(View.VISIBLE);
                mAdapter.notifyDataSetChanged();
            }
        });
        mBinding.tvFinish.setVisibility(View.VISIBLE);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v.getId() == R.id.tv_finish) {
            if (ClickUtils.isDoubleClick()) {
                return;
            }
            EventBus.getDefault().post(AgentApplyEvent.Companion.make(EventConstant.EVENT_AGENT_APPLY_CHOOSE_DEPT_SUCCESS, mEntity));
            finish();
        }
    }

    @Override
    protected void init() {
        super.init();
        if (mDatas == null) {
            mViewModel.getCompanyList(this);
        }
    }

    private void updateFirstDepartment(String name, boolean isHighlight) {
        mBinding.tvCompany.setText(name);
        mBinding.tvCompany.setTextColor(getResources().getColor(!isHighlight ? R.color.color_title_small : R.color.color_secondary_blue));
    }

    private void updateSecondDepartment(String name, boolean isHighlight) {
        if (mBinding.linHeader.getChildCount() < 2){
            tvSecondName = new TextView(this);
            tvSecondName.setCompoundDrawablePadding(SizeUtils.dp2px(5f));
            tvSecondName.setGravity(Gravity.CENTER);
            mBinding.linHeader.addView(tvSecondName);
        }
        tvSecondName.setCompoundDrawablesWithIntrinsicBounds (TextUtils.isEmpty(name) ? null : getResources().getDrawable(R.drawable.icon_right_arrow_small),
                null, null, null);
        tvSecondName.setTextColor(getResources().getColor(!isHighlight ? R.color.color_title_small : R.color.color_secondary_blue));
        tvSecondName.setText(name);
    }


    class AgentStaffDepartmentAdapter extends BaseQuickAdapter<CompanyAndDeptEntity, BaseViewHolder>{
        private boolean isShowRight = false;
        private OnItemClickCallBack mCallBack;

        private ItemAgentStaffDepartmentBinding mItemBinging;

        public boolean isShowRight() {
            return isShowRight;
        }

        public void setShowRight(boolean showRight) {
            isShowRight = showRight;
        }

        public void setCallBack(OnItemClickCallBack mCallBack) {
            this.mCallBack = mCallBack;
        }

        public AgentStaffDepartmentAdapter(int layoutResId) {
            super(layoutResId);
        }

        @Override
        protected void convert(BaseViewHolder helper, CompanyAndDeptEntity item) {
            mItemBinging = DataBindingUtil.bind(helper.itemView);
            if (mItemBinging != null){
                mItemBinging.setViewModel(item);
                mItemBinging.executePendingBindings();
                mItemBinging.ivNext.setVisibility(isShowRight || (item.getChildren() != null && !item.getChildren().isEmpty()) ? View.VISIBLE : View.GONE);
                mItemBinging.ivChoose.setImageResource(item.isChoose() ?  R.drawable.ic_anonymity_selected : R.drawable.ic_anonynity_normal);
                mItemBinging.ivChoose.setOnClickListener(v -> {
                    if (mCallBack != null){
                        mCallBack.changeChooseStats(helper.getLayoutPosition());
                    }
                });
                mItemBinging.getRoot().setOnClickListener(v -> {
                    if (mCallBack != null){
                        mCallBack.itemClick(helper.getLayoutPosition());
                    }
                });
            }
        }
    }

    interface OnItemClickCallBack{
        void changeChooseStats(int position);
        void itemClick(int position);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(AgentApplyEvent event){
        if (event.getMessageTag() == EventConstant.EVENT_AGENT_APPLY_CHOOSE_DEPT_SUCCESS){
            finish();
        }
    }
}
